﻿using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace Lhz.Serialization
{
    public class BinarySerializer : Serializer<byte[]>
    {
        public override byte[] Serialize<TObject>(TObject item)
        {
            using (var ms = new MemoryStream())
            {
                var bf = new BinaryFormatter();
                bf.Serialize(ms, item);
                ms.Position = 0;
                byte[] read = new byte[ms.Length];
                ms.Read(read, 0, read.Length);
                return read;
            }
        }

        public override object Deserialize(Type type, byte[] content)
        {
            using (var ms = new MemoryStream(content))
            {
                ms.Position = 0;
                return new BinaryFormatter().Deserialize(ms);
            }
        }
    }
}
